import 'package:flutter/material.dart';
import 'package:flutter_navigator/OSNavigator/OSNavigator.dart';
import 'package:flutter_navigator/Pages/AlarmPage.dart';
import 'package:flutter_navigator/Pages/HomeDetailPage.dart';
import 'package:flutter_navigator/Pages/HomePage.dart';
import 'package:flutter_navigator/Pages/Model/VideoModel.dart';
import 'package:flutter_navigator/Pages/Portal/LoginPage.dart';
import 'package:flutter_navigator/Pages/Portal/RegistPage.dart';

import 'OSNavigator/OSTabBarNavigator.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  OSRouterDelegate _routerDelegate = OSRouterDelegate();

  @override
  Widget build(BuildContext context) {
    //定义Router
    var widget = Router(
      routerDelegate: _routerDelegate,
    );
    return MaterialApp(
      home: widget,
    );
  }
}

class OSRouterDelegate extends RouterDelegate<OSRoutePath>
    with ChangeNotifier, PopNavigatorRouterDelegateMixin<OSRoutePath> {
  final GlobalKey<NavigatorState> navigatorKey;
  //为Navigator设置一个key,必要时候可以通过navigatorKey.currentState来获取到NavigatorState对象
  OSRouterDelegate() : navigatorKey = GlobalKey<NavigatorState>() {
    //实现跳转逻辑
    OSNavigator.getInstance().registerRouteJump(
        RouteJumpListener(onJumpTo: (RouteStatus routeStatus, {Map? args}) {
      _routeStatus = routeStatus;
      if (routeStatus == RouteStatus.homeDetail) {
        this.videoModel = args!["videoModel"];
      } else if (routeStatus == RouteStatus.home) {
        if (args != null) {
          _loginSuccess = args["isLogin"];
        }
      }
      notifyListeners();
    }));
  }
  RouteStatus _routeStatus = RouteStatus.home;
  List<MaterialPage> pages = [];
  VideoModel? videoModel;

  /// 登陆成功保存token
  bool _loginSuccess = false;

  @override
  Widget build(BuildContext context) {
    var index = getPageIndex(pages, routeStatus);
    List<MaterialPage> temPages = pages;
    if (index != -1) {
      // 当要打开的页面在栈中已经存在，则将该页面和它上面的所有页面进行出栈操作
      temPages = temPages.sublist(0, index);
    }
    var page;
    if (routeStatus == RouteStatus.home) {
      //跳转到首页将栈中其他页面进行出栈，因为首页不可回退
      pages.clear();
      page = pageWarp(OSTabBarNavigator());
    } else if (routeStatus == RouteStatus.homeDetail) {
      page = pageWarp(AMHomeDetailPage(videoModel!));
    } else if (routeStatus == RouteStatus.login) {
      page = pageWarp(AMLoginPage());
    } else if (routeStatus == RouteStatus.regist) {
      page = pageWarp(AMRegistPage());
    } else if (routeStatus == RouteStatus.alarm) {
      page = pageWarp(AMAlarmPage());
    }

    // 重新创建一个数组，否则pages因为引用没有改变路由不会生效
    temPages = [...temPages, page];
    //通知路由发生变化
    OSNavigator.getInstance().notify(temPages, pages);
    pages = temPages;

    return WillPopScope(
      onWillPop: () async => !await navigatorKey.currentState!.maybePop(),
      child: Navigator(
        key: navigatorKey,
        pages: pages,
        onPopPage: (route, result) {
          //在这里可以控制是否返回
          if (!route.didPop(result)) {
            return false;
          }
          //通知路由发生改变
          var temPages = [...pages];
          pages.removeLast();
          OSNavigator.getInstance().notify(pages, temPages);
          return true;
        },
      ),
    );
  }

  RouteStatus get routeStatus {
    if (_routeStatus != RouteStatus.regist && !hasLogin) {
      return _routeStatus = RouteStatus.login;
    } else if (videoModel != null) {
      return _routeStatus = RouteStatus.homeDetail;
    } else {
      return _routeStatus;
    }
  }

  // 是否登陆校验（暂时默认为true）
  bool get hasLogin => _loginSuccess;

  @override
  Future<void> setNewRoutePath(OSRoutePath configuration) async {}
}

/// 定义路由数据
class OSRoutePath {
  final String location;
  OSRoutePath.home() : location = "/";
  OSRoutePath.detail() : location = "/detail";
}
